package com.atguigu.gulimall.ware.listener;

import com.atguigu.common.to.mq.OrderTo;
import com.atguigu.common.to.mq.StockLockedTo;
import com.atguigu.gulimall.ware.service.WareSkuService;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
/**
 * RabbitMQ 监听器
 */
@Service
@RabbitListener(queues = "stock.dead.queue")    //监听库存的死信队列
public class StockReleaseListener {
    @Autowired private WareSkuService wareSkuService;

    @RabbitHandler
    public void HandlerStockLockerRelease(StockLockedTo stockLockedTo, Message message, Channel channel) throws Exception {
        System.out.println("收到解锁库存的消息...");
        try{
            wareSkuService.unlockStock(stockLockedTo);    //调用《解锁库存》方法
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        }catch (Exception e){
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);    //true：消费失败，则重新入队
        }}

    @RabbitHandler
    public void HandlerOrderCloseRelease(OrderTo orderTo, Message message, Channel channel) throws IOException {
        System.out.println("订单关闭，准备解锁库存的消息...");
        try{
            wareSkuService.unLockStockForOrder(orderTo);    //调用《按照 工作单id 找到所有 没有解锁的库存，进行解锁》方法
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        }catch (Exception e){
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), true); //true：消费失败，则重新入队
        }}
}
